package com.supinfo.bonjoursupinfo.fragments;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.supinfo.bonjoursupinfo.R;
import com.supinfo.bonjoursupinfo.adapters.NewsAdapter;
import com.supinfo.bonjoursupinfo.controller.NewsController;
import com.supinfo.bonjoursupinfo.controller.NewsController.OnReloadListener;
import com.supinfo.bonjoursupinfo.database.NewsBDD;
import com.supinfo.bonjoursupinfo.models.News;

public class NewsFragment extends Fragment {

	private View view;
	private PullToRefreshListView newsList;
	private NewsController nc;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setHasOptionsMenu(true);
	}

	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.list_view_news, container, false);
		newsList = (PullToRefreshListView) view.findViewById(R.id.listViewNews);
		
		nc = new NewsController(this);
		nc.setOnReloadListener(onReloadListener);
		nc.execute();

		return showNews();
	}
	
	private OnReloadListener onReloadListener = new OnReloadListener(){

		@Override
		public void onReload() {
			newsList.onRefreshComplete();
			showNews();
		}
		
	};

	public View showNews() {
		if(this.getActivity() == null){
			return view;
		}
		List<News> newList = GetAllNews();
		if(newList == null){
			newList = new ArrayList<News>();
		}
		NewsAdapter newsAdapter = new NewsAdapter(this.getActivity(),
				R.layout.item_newslist, newList);
		newsList.setAdapter(newsAdapter);
		//newsList.refreshDrawableState();
		newsList.setOnRefreshListener(new OnRefreshListener<ListView>(){
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				nc = new NewsController(getFragment());
				nc.setOnReloadListener(onReloadListener);
				nc.execute();
				view = showNews();
			}
		});	
		return view;
	}

	public NewsFragment getFragment(){
		return this;
	}

	public List<News> GetAllNews() {
		NewsBDD newsbdd = new NewsBDD();
		newsbdd.open();
		List<News> list = newsbdd.getAllNews();
		newsbdd.close();
		return list;
	}

}